package dbAccess;
import java.io.*;
import java.sql.*;
import java.lang.*;

/* This is just to begin the data access layer.*/
public class DbAccess {
	
	public Connection connect(String connectURL, String userName, String password)
	{
		Connection conn;
		try
		{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(connectURL, userName, password);
		}
 		catch (Exception e)
		{
			conn = null;
			System.out.print(e.getMessage());
		}
		return conn;
	}
	
	public Connection connect()
	{
		//default connection
		return connect("jdbc:mysql://localhost:3306/test","root","test");
	}
	
	public ResultSet ExecuteSelect(Connection con, String query)
	{
		try
		{
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery(query);
			return rs;
		} 
		catch(SQLException e)
		{
			System.out.print(e.getMessage());
			return null;
		}
	}
	
	public String ExecuteScalar(Connection con, String query)
	{
		try
		{
			ResultSet rs = ExecuteSelect(con, query);
			rs.next();
			String retString = rs.getString(1); 
			CloseConnection(con);
			return retString; 
		} 
		catch(SQLException e)
		{
			System.out.print(e.getMessage());
			CloseConnection(con);
			return null;
		}
	}

	public Boolean ExecuteUpdate(Connection con, String query)
	{
		try
		{
			Statement st = con.createStatement();
			st.executeUpdate(query);
			CloseConnection(con);
			return true;
		}
		catch(SQLException e)
		{
			System.out.print(e.getMessage());
			CloseConnection(con);
			return false;
		}
	}

	public void CloseConnection(Connection con)
	{
		try
		{
			if(!con.isClosed())
				con.close();
		}
		catch(SQLException e)
		{
		}
	}
		
}
